<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动标题" prop="activityTitle">
        <el-input
          v-model="queryParams.activityTitle"
          placeholder="请输入活动标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报名状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="报名状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['secondclass:enrollment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['secondclass:enrollment:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['secondclass:enrollment:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['secondclass:enrollment:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="multiple"
          @click="handleBatchSignIn"
          v-hasPermi="['secondclass:enrollment:edit']"
        >批量签到</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="enrollmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="报名ID" align="center" prop="enrollmentId" width="80" />
      <el-table-column label="活动标题" align="center" prop="activityTitle" :show-overflow-tooltip="true" />
      <el-table-column label="用户名称" align="center" prop="userName" width="120" />
      <el-table-column label="报名状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag :type="statusTypeMap[scope.row.status]">{{ scope.row.statusName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="签到时间" align="center" prop="signTime" width="160">
        <template slot-scope="scope">
          <span v-if="scope.row.signTime">{{ parseTime(scope.row.signTime) }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="报名时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['secondclass:enrollment:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['secondclass:enrollment:remove']"
          >删除</el-button>
          <el-dropdown size="mini" @command="handleCommand" trigger="click">
            <span class="el-dropdown-link">
              <i class="el-icon-arrow-down el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item 
                :command="{ type: 'approve', row: scope.row }" 
                v-if="scope.row.status === '0'"
                v-hasPermi="['secondclass:enrollment:edit']"
              >审核通过</el-dropdown-item>
              <el-dropdown-item 
                :command="{ type: 'reject', row: scope.row }" 
                v-if="scope.row.status === '0'"
                v-hasPermi="['secondclass:enrollment:edit']"
              >审核拒绝</el-dropdown-item>
              <el-dropdown-item 
                :command="{ type: 'signin', row: scope.row }" 
                v-if="scope.row.status === '1' && !scope.row.signTime"
                v-hasPermi="['secondclass:enrollment:edit']"
              >签到</el-dropdown-item>
              <el-dropdown-item 
                :command="{ type: 'addCredit', row: scope.row }" 
                v-if="scope.row.status === '3'"
                v-hasPermi="['secondclass:credit:add']"
              >添加学分记录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改活动报名对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="活动" prop="activityId">
          <activity-select v-model="form.activityId" placeholder="请选择活动" />
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="报名状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择报名状态">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEnrollment, getEnrollment, addEnrollment, updateEnrollment, updateEnrollmentStatus, signInEnrollment, batchSignIn, delEnrollment } from "@/api/secondclass/enrollment";
import ActivitySelect from "@/components/ActivitySelect";

export default {
  name: "Enrollment",
  components: { ActivitySelect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 活动报名表格数据
      enrollmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态类型映射
      statusTypeMap: {
        "0": "info",
        "1": "success",
        "2": "danger",
        "3": "primary",
        "4": "warning"
      },
      // 状态数据字典
      statusOptions: [
        {
          dictLabel: "待审核",
          dictValue: "0"
        },
        {
          dictLabel: "已通过",
          dictValue: "1"
        },
        {
          dictLabel: "已拒绝",
          dictValue: "2"
        },
        {
          dictLabel: "已签到",
          dictValue: "3"
        },
        {
          dictLabel: "未签到",
          dictValue: "4"
        }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activityId: null,
        activityTitle: null,
        userId: null,
        userName: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        activityId: [
          { required: true, message: "活动不能为空", trigger: "change" }
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "报名状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    // 从URL参数中获取活动ID
    if (this.$route.query.activityId) {
      this.queryParams.activityId = this.$route.query.activityId;
    }
    this.getList();
  },
  methods: {
    /** 查询活动报名列表 */
    getList() {
      this.loading = true;
      listEnrollment(this.queryParams).then(response => {
        this.enrollmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        enrollmentId: null,
        activityId: this.queryParams.activityId || null,
        userId: null,
        status: "0",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.enrollmentId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加活动报名";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const enrollmentId = row.enrollmentId || this.ids[0];
      getEnrollment(enrollmentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改活动报名";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.enrollmentId != null) {
            updateEnrollment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEnrollment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const enrollmentIds = row.enrollmentId || this.ids;
      this.$modal.confirm('是否确认删除活动报名编号为"' + enrollmentIds + '"的数据项?').then(function() {
        return delEnrollment(enrollmentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('secondclass/enrollment/export', {
        ...this.queryParams
      }, `enrollment_${new Date().getTime()}.xlsx`);
    },
    /** 批量签到按钮操作 */
    handleBatchSignIn() {
      this.$modal.confirm('确认要对选中的报名进行签到操作吗?').then(() => {
        return batchSignIn(this.ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("批量签到成功");
      }).catch(() => {});
    },
    /** 处理下拉菜单命令 */
    handleCommand(command) {
      const { type, row } = command;
      switch (type) {
        case 'approve':
          this.handleUpdateStatus(row, '1');
          break;
        case 'reject':
          this.handleUpdateStatus(row, '2');
          break;
        case 'signin':
          this.handleSignIn(row);
          break;
        case 'addCredit':
          this.handleAddCredit(row);
          break;
        default:
          break;
      }
    },
    /** 更新报名状态 */
    handleUpdateStatus(row, status) {
      const statusMap = {
        '1': '审核通过',
        '2': '审核拒绝'
      };
      this.$modal.confirm('确认要' + statusMap[status] + '该报名吗?').then(() => {
        return updateEnrollmentStatus(row.enrollmentId, status);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(statusMap[status] + "成功");
      }).catch(() => {});
    },
    /** 签到操作 */
    handleSignIn(row) {
      this.$modal.confirm('确认要对该报名进行签到操作吗?').then(() => {
        return signInEnrollment(row.enrollmentId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("签到成功");
      }).catch(() => {});
    },
    /** 添加学分记录 */
    handleAddCredit(row) {
      this.$router.push({ 
        path: '/secondclass/credit/add', 
        query: { 
          activityId: row.activityId,
          userId: row.userId
        } 
      });
    }
  }
};
</script>
